package http_middleware

import (
	"bytes"
	"gitee.com/zaper/private-logger"
	"gitee.com/zaper/software-framework/util"
	"github.com/gin-gonic/gin"
	"io"
)

// HotResponseWriter 用于捕获响应内容
type HotResponseWriter struct {
	gin.ResponseWriter
	body *[]byte
}

func (w HotResponseWriter) Write(b []byte) (int, error) {
	// 记录响应内容到 body
	*w.body = append(*w.body, b...)
	// 调用原始 ResponseWriter 的 Write 方法
	return w.ResponseWriter.Write(b)
}

func ControllerLogFilter() gin.HandlerFunc {
	return func(context *gin.Context) {

		// 初始化用于存储响应内容的切片
		responseBody := make([]byte, 0)
		// 替换 ctx.Writer
		writer := &HotResponseWriter{
			ResponseWriter: context.Writer,
			body:           &responseBody,
		}
		context.Writer = writer

		// 打印请求信息
		requestBody, _ := io.ReadAll(context.Request.Body)
		// 注意：读取完请求体后，需重新赋值回 ctx.Request.Body，否则后续处理拿不到请求体
		context.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
		logger.Infof("[Controller request] ------ url is %s, body is %s", context.Request.URL, string(requestBody))
		startTime := util.GetCurrentTimeStamp()
		// 继续执行后续中间件和处理函数
		context.Next()
		// 打印响应信息
		logger.Infof("[Controller response] ------ url is %s, body is %s, cost time %d ms", context.Request.URL,
			string(responseBody), util.GetCurrentTimeStamp()-startTime)
	}
}
